package com.zsd.android.okhttplib;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求体
 */
public class RequestBody {

    //表单提交Type application/x-www-form-urlencoded
    public static final String TYPE = "application/x-www-form-urlencoded";

    public static final String ENC = "UTF-8";

    //请求体集合
    private Map<String, String> bodys;

    public RequestBody() {
        bodys = new HashMap<>();
    }

    /**
     * 添加请求体信息
     * @param key
     * @param value
     */
    public void addBody(String key, String value) {
        //需要编码
        try {
            bodys.put(URLEncoder.encode(key, ENC), URLEncoder.encode(value, ENC));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public String getBody() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : bodys.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key);
            sb.append("=");
            sb.append(value);
            sb.append("&");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}
